<?php

namespace App\Http\Service\Douban;

use App\Models\Doubanpostproduct;
use App\Models\Doubanlog;
use App\Models\Doubanlike;
use App\Models\Doubancollect;
use App\Http\Service\UserService;
use App\Http\Service\Douban\DoubanpostimageService;
use App\Http\Service\BaseService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use App\Http\Service\ContentScoringService;
use App\Http\Service\PlatformsService;
use App\Http\Service\MoneyService;


class DoubanpostproductService  extends BaseService
{
    private $model;
    public $URL_MAP;
    public $getInfo;
    public function __construct(Doubanpostproduct $model,UserService $userService,Doubanlog $doubanlog,DoubanpostimageService $DoubanpostimageService,Doubanlike $doubanlike,PlatformsService $PlatformsService,MoneyService $moneyService)
    {
        parent::__construct();
        $this->URL_MAP=config('myurl.URL_MAP');
        $this->getInfo=config('myurl.getInfo');
        $this->model = $model;
        $this->doubanlog = $doubanlog;
        $this->userService = $userService;
        $this->DoubanpostimageService = $DoubanpostimageService;
        $this->doubanlike = $doubanlike;
        $this->platformsService=$PlatformsService;
        $this->moneyService=$moneyService;
    }
   
    /**
     * 帖子里边关联商品添加
     * @param array $params
     * @return array
     */
    public function addData($request,$user_id,$post_unique_id,$guanlian_shop)
    {
        $guanlian_shop=json_decode($guanlian_shop,true);

        //dd($guanlian_shop);
        //获取所有json数据
        $jsonData = $request->json()->all();
        $jsonData=json_encode($jsonData, JSON_UNESCAPED_UNICODE);

        foreach ($guanlian_shop as $k => $v) {
            $title=$v['title'];
            $image=$v['image'];
            $avatar="";
            $nickname="";
            if(!empty($user_id) && $user_id>=1000){
               $user_info=$this->userService->update_user($user_id);
               $nickname=$user_info['nickname'];
               $avatar=$user_info['avatar'];
               
            }
            $platform_name=$v['platformName'];
            $getinfo_url=$this->getInfo;
            $user_params=[
                "product_id"=>$v['productId'],
                "platform"=> $platform_name,
                "user_id"=> $user_id

            ];
            #测试
/*            $user_params=[
                "product_id"=>'564331706096',
                "platform"=> '淘宝',
                "user_id"=> '1227'

            ];*/

            $data=json_post($getinfo_url,$user_params);
            $user_data=$data=$data['data'];
            //dd($data);

            //原价
            if(isset($data['origain_price'])){
                $origain_price=$data['origain_price'];
            }else{
                $origain_price=0.00;
            }
            if(empty($origain_price)){
                $origain_price=0.00;
            }
            
           // dd($origain_price);

            //佣金比例
            if(isset($data['commission_rate'])){
                $commission_rate=$data['commission_rate'];
            }else{
                $commission_rate=0.00;
            }
            
            if(empty($commission_rate)){
                $commission_rate=0.00;
            }
            $commission_rate=$commission_rate*100;
            //数量
            $quantity=1;
            if(empty($quantity)){
                $quantity=1;
            }
            //单价
            if(isset($data['final_price'])){
                $unit_price=$data['final_price'];
            }else{
                $unit_price=0.00;
            }
            
            if(empty($unit_price)){
                $unit_price=1;
            }
            //下单价
            $final_price=$unit_price*$quantity;
            //佣金金额
            if(isset($data['commission'])){
                $commission_amount=$data['commission'];
            }else{
                $commission_amount=0.00;
            }
            if(empty($data['commission'])){
                $commission_amount=0.00;
            }
            
            //佣金总金额
            $commission_amount_total=$commission_amount*$quantity;
            #京东plus佣金描述
            if(isset($data['jd_plus_commission_desc'])){
                $jd_plus_commission_desc=$data['jd_plus_commission_desc'];
            }else{
                $jd_plus_commission_desc='';
            }
            
            $product_id=$data['product_id'];
            $product_unique_id=$data['product_id_suffix'];
            #官方补贴活动 2(默认没有官方补贴活动)
            $is_subsidy=2;
            $subsidy_rate=0.00;
            $subsidy_amount=0.00;
            $subsidy_name="";
            //dd($data);
            if(isset($data['platform_subsidy'])){
                
                $platform_subsidy=$data['platform_subsidy'];
                if(isset($platform_subsidy[0])){
                    $platform_subsidy=$platform_subsidy[0];
                    //dd($platform_subsidy['subsidy_rate']);
                    if(isset($platform_subsidy['subsidy_rate'])){
                       // dd($platform_subsidy);
                        $is_subsidy=1;
                        $subsidy_rate=$platform_subsidy['subsidy_rate'];

                    }
                    if(isset($platform_subsidy['subsidy_amount'])){
                        $subsidy_amount=$platform_subsidy['subsidy_amount'];
                    }

                    if(isset($platform_subsidy['subsidy_name'])){
                        $subsidy_name=$platform_subsidy['subsidy_name'];
                    }

                }
                
                ///dd($subsidy_amount);

            }




            $steps_plan=$user_data['steps_plan'];
                //dd($steps_plan);
                $purchase_youhuiquan=[];
                if(isset($steps_plan['duojian_step']) && !empty($steps_plan['duojian_step']['coupon_list']))
                {
                    //优惠券
                    $coupon_list=$steps_plan['duojian_step']['coupon_list'];
                    foreach($coupon_list as $k=>$v){
                        $purchase_youhuiquan[]=[
                            'type'=>1,
                            'title'=>'优惠券',
                            'description'=>$v['coupon_title'],
                            'link'=>$v['coupon_url'],
                            'platform'=>$user_params['platform'],
                        ];
                    }

                }
                $purchase_huodong=[];
                if(isset($steps_plan['duojian_step']) && !empty($steps_plan['duojian_step']['discount_desc']))
                {
                    //活动
                    $discount_desc=$steps_plan['duojian_step']['discount_desc'];
                    foreach($discount_desc as $k=>$v){
                        $purchase_huodong[]=[
                            'type'=>2,
                            'title'=>'活动',
                            'description'=>$v,
                            'link'=>'',
                            'platform'=>$user_params['platform'],
                        ];
                    }


                }

                $content='';
                if(isset($steps_plan['duojian_step']) && !empty($steps_plan['duojian_step']['price_desc']))
                {
                    //推荐方案
                    $content=$steps_plan['duojian_step']['price_desc'];
                    

                }



            $purchase=[];
            $purchase_steps=[];
            //dd($purchase_huodong);

            if(!empty($purchase_youhuiquan)){
                $purchase_steps=array_merge($purchase,$purchase_youhuiquan);
            }
            if(!empty($purchase_huodong)){
                $purchase_steps=array_merge($purchase_steps,$purchase_huodong);
            }
            /*if(!empty($purchase_jiagou)){
                $purchase_steps=array_merge($purchase_steps,$purchase_jiagou);
            }
            if(!empty($purchase_coudan)){
                $purchase_steps=array_merge($purchase_steps,$purchase_coudan);
            }*/
            $brand="";
            if(isset($user_data['brand'])){
                $brand=$user_data['brand'];
            }
            $standard_category="";
            if(isset($user_data['standard_category'])){
                $standard_category=$user_data['standard_category'];
            }
            $img="";
            if(isset($user_data['img'])){
                $img=$user_data['img'];
            }

            $screen_img="";
            if(isset($user_data['screen_img'])){
                $screen_img=$user_data['screen_img'];
            }
            if(empty($subsidy_rate)){
                $subsidy_rate=0.00;
            }
            $subsidy_rate=$subsidy_rate*100;
            $quantity=1;

            $post_data=[
                'unique_id'=>generateRandomString(),
                'brand_name'=>$brand,
                'category_name'=>$standard_category,
                "cover" => $img,
                "purchase_steps" =>$purchase_steps,
                'post_unique_id'=>$post_unique_id,
                "purchase_screenshots" =>[],
                'user_id'=>$user_id,
                'platform_name'=>$platform_name,
                'nickname'=>$nickname,
                'avatar'=>$avatar,
                'origain_price'=>$origain_price,
                'product_id'=>$product_id,
                'product_unique_id'=>$product_unique_id,
                'unit_price'=>$unit_price,
                'quantity'=>$quantity,
                'final_price'=>$final_price,
                'commission_rate'=>$commission_rate,
                'commission_amount'=>$commission_amount,
                'commission_amount_total'=>$commission_amount_total,
                'jd_plus_commission_desc'=>$jd_plus_commission_desc,
                'json_data'=>$jsonData,
                'title'=>$title,
                'images'=>$screen_img,
                "begin_time" => '',
                "content" => $content,
                'start_time'=>'',
                'end_time'=>'',
                'publish_time'=>date("Y-m-d H:i:s"),
                'subsidy_rate'=>$subsidy_rate,
                'subsidy_amount'=>$subsidy_amount,
                'subsidy_name'=>$subsidy_name

            ];


            $platform_name=$post_data['platform_name'];
            //活动，优惠，加购，凑单，下单
            $purchase_steps=$post_data['purchase_steps'];

            #组装数据
            foreach ($purchase_steps as $k=> &$v) {
                switch ($v['type']) {
                    case '1':
                        $v['data-dimension122']="优惠券";
                        $v['tag_text']=$v['description'];
                        $v['you_hui_tiao_zhuan_link_end']='';
                        $v['huo_dong_time']='';
                        break;
                    case '2':
                        if(isset($v['link'])&&empty($v['link'])){
                            //unset($purchase_steps[$k]);
                        }else{
                            $v['data-dimension122']="活动";
                            $v['tag_text']=$v['description'];
                            $v['you_hui_tiao_zhuan_link_end']='';
                            $v['huo_dong_time']='';
                        }
                        
                        break;
                    case '3':
                        $v['data-dimension122']="加购";
                        $v['tag_text']=$v['description'];
                        $v['you_hui_tiao_zhuan_link_end']='';
                        $v['huo_dong_time']='';
                        break;
                    case '4':
                        $v['data-dimension122']="凑单";
                        $v['tag_text']=$v['description'];
                        $v['you_hui_tiao_zhuan_link_end']='';
                        $v['huo_dong_time']='';
                        break;
                    default:
                }


            }

            if(!isset($this->URL_MAP[$platform_name])){
                $this->error("平台不存在,请联系管理员添加平台[{$platform_name}]");
            }


            $url=$this->URL_MAP[$platform_name];
            $productId=$post_data['product_id'];
            $platform =$post_data['platform_name'];
            $final_price=$post_data['final_price'];
            $commission_amount_total =$post_data['commission_amount_total'];
            //是否是产品
            $fetch_platform_data=fetch_platform_data($platform_name,$productId,$url);
            $is_product=1;
            $product_list=[];
            if($fetch_platform_data){
                $product_list[]=[
                    'type'=> 'link',
                    'text'=> $fetch_platform_data['productUrl'],
                    'title'=> $fetch_platform_data['title'],
                    'productImage'=> $fetch_platform_data['productImage'],
                    'productName'=> $fetch_platform_data['productName'],
                    'product_id'=> $fetch_platform_data['item_id'],
                    'platform_name'=> $platform,
                    'link_text'=> '',
                ];

            }else{
                $is_product=0;
            }

            $link="";
            if(!empty($product_list)){
                $link=$product_list[0]['text'];
            }
            
            //加购
            $purchase_steps[]=[
                "data-dimension122"=> "加购",
                "type"=>3,
                "tag_text"=> "下单{$quantity}件-{$post_data['title']}",
                "you_hui_tiao_zhuan_link_end"=> "",
                "huo_dong_time"=> null,
                "platform"=>$platform_name,
                "title"=> "加购",
                "description"=> "下单{$quantity}件-{$post_data['title']}",
                "link"=>$link,

            ];
            //$quantity=1;
            //下单
            if($quantity>1){

                $lastunitPrice = $unit_price-$commission_amount;
                //dd($commission_amount);
                //$shifu=$unit_price*$quantity;
                $lastunitPrice =_round($lastunitPrice);
                $purchase_steps[]=[
                    "data-dimension122"=> "下单",
                    "title"=> "下单",
                    "type"=> 5,
                    "description"=> "下单{$quantity}件实付{$final_price}，下单后返利约{$commission_amount_total}元，单价合{$lastunitPrice}元",
                    "link"=>'',
                    "platform"=>'',
                ];
            }else{
                $purchase_steps[]=[
                    "data-dimension122"=> "下单",
                    "type"=> 5,
                    "title"=> "下单",
                    "description"=> "实付{$final_price}，下单后返利约{$commission_amount_total}元",
                    "link"=>'',
                    "platform"=>'',
                ];
            }
           // dd($purchase_steps);
            $purchase_steps=array_values($purchase_steps);
            $post_data['purchase_steps'] = json_encode($purchase_steps, JSON_UNESCAPED_UNICODE);

            $post_data['images'] = json_encode($post_data['images'], JSON_UNESCAPED_UNICODE);
            $post_data['purchase_screenshots'] = json_encode($post_data['purchase_screenshots'], JSON_UNESCAPED_UNICODE);
            //dd($post_data);

            #先删除以前数据
            $this->model->where(['post_unique_id'=>$post_unique_id])->delete();

            
            $post_data['create_time'] =date("Y-m-d H:i:s");
            $post_data['update_time'] =date("Y-m-d H:i:s");
            $post_id=$this->model->insertGetId($post_data);
            //dd($post_id);

        }
        

       
    }


    //逛逛详情
    public function dataDetail($request,$data=[])
    {
        //用户id
        $people_id=$data['people_id'];

        #项目类型 =1 爆料项目  =2 心动日记
        $item_type=$data['item_type'];


        $unique_id=$data['unique_id'];

        $where = [
           ['unique_id','=',$unique_id],
        ];
        //
        $list = $this->model->where($where)->select(['id','unique_id','purchase_steps','purchase_screenshots','title','images','avatar','nickname','cover','begin_time','content','create_time','update_time','unit_price','quantity','final_price','commission_rate','commission_amount','commission_amount_total','product_id','product_unique_id','user_id','platform_name','start_time','end_time','publish_time'])->first();
        if(empty($list)){
            $this->error("没有数据");
        }

        $likeList=Doubanlike::getList();
        $collectList=Doubanlike::getList();
        # 判断状态
        $key="{$list['unique_id']}_{$people_id}";

        $list['is_like'] =2;
        if(isset($likeList[$key])){
            $list['is_like'] =1;
        }
        $list['is_collect'] =2;
        if(isset($collectList[$key])){
            $list['is_collect'] =1;
        }



        $is_owner=$list['is_owner'];
        if(empty($list['is_owner'])){
            $is_owner=true;
        }
        $unit_price=$list['unit_price'];
        if(empty($unit_price)){
            $unit_price=0.00;
        }
        $subsidy_rate=$list['subsidy_rate'];
        if(empty($subsidy_rate)){
            $subsidy_rate=0.00;
        }
        $subsidy_rate=$subsidy_rate/100;

        $commission_rate=$list['commission_rate'];
        if(empty($commission_rate)){
            $commission_rate=0.00;
        }
        $commission_rate=$commission_rate/100;
        
        $platform_name=$list['platform_name'];

        $people_id=$data['people_id'];
        if(empty($people_id)){
            $people_id=206292;
        }
        $quantity=$list['quantity'];
        $title=$list['title'];

        #预估返
        $estimatedTotalCommission=$this->moneyService->get_total_commission_ing($unit_price,$subsidy_rate,$commission_rate,$platform_name,$people_id,$is_rate_true=0,$is_owner,$item_type);
       // dd($estimatedTotalCommission);

        $total_commission=$estimatedTotalCommission['total_commission'];
        //dd($estimatedTotalCommission);
        $list['commission_amount']=$estimatedTotalCommission['total_commission'];
        #保留两位小数
        $list['commission_amount']=_round($list['commission_amount']);

        //dd($list['commission_amount']);

        //用户id
        $userlist=$this->userService->update_user($list['user_id']);
        $list['nickname'] =$userlist['nickname'];
        $list['avatar'] =$userlist['avatar'];


        $list['purchase_steps'] =json_decode($list['purchase_steps'],true);

        #重写购买步骤
        $list['purchase_steps'] =$this->moneyService->purchase_steps($list['purchase_steps'],$quantity,$title,$platform_name,$total_commission,$unit_price);

        $list['purchase_screenshots'] =json_decode($list['purchase_screenshots'],true);
        
        return $list;
    }
    
}
